//
//  SwiftConst.swift
//  SwiftInOC
//
//  Created by  on 2017/12/1.
//  Copyright © 2017年 Anna. All rights reserved.
//

// MARK: - Library
import Foundation
import UIKit
import SnapKit
import Kingfisher
import AVFoundation

// MARK: - 用于判断 wifi 是否链接
var mPCIpAddress:String?    // WiFi Ip地址
var mPCIpAddressData:Data?  // WiFi Ip地址
var XSQ_NetWorkType = 1

// MARK: - Const
let XSQ_Screen          = UIScreen.main.bounds
let XSQ_Width           = UIScreen.main.bounds.width
let XSQ_Height          = UIScreen.main.bounds.height
let XSQ_StatusNav       = UIApplication.shared.statusBarFrame.height + 44
let XSQ_Tab:CGFloat     = XSQ_StatusNav == 88 ? 83 : 49

let XSQ_ColorLightGray       = UIColor.init(red: 242/255.0, green: 242/255.0, blue: 242/255.0, alpha: 1)

let XSQ_ColorYellow     = UIColor.init(red: 253/255.0, green: 208/255.0, blue: 0/255.0, alpha: 1)
let XSQ_ColorGreen      = UIColor.init(red: 30/255.0, green: 188/255.0, blue: 114/255.0, alpha: 1)
let XSQ_ColorOrange     = UIColor.init(red: 255/255.0, green: 164/255.0, blue: 27/255.0, alpha: 1)
let XSQ_ColorRed        = UIColor.init(red: 230/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1)
let XSQ_ColorBlue       = UIColor.init(red: 46/255.0, green: 165/255.0, blue: 252/255.0, alpha: 1)
let XSQ_ColorBackground = setBackgroundColor()
let XSQ_ColorText       = setTextColor()
let XSQ_PasswordRule    = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"

// MARK: - Application programming interface Parents
 
func isJPEG(_ string: String) -> Bool {
    let lowerString = string.lowercased()
    return lowerString.hasSuffix(".jpg") || lowerString.hasSuffix(".jpeg") || lowerString.hasSuffix(".png") || lowerString.hasSuffix(".heic")
}

// MARK: - Date components
func XSQcomponents(date:Date) -> DateComponents {
    let components = Calendar.current.dateComponents([Calendar.Component.year,Calendar.Component.month,Calendar.Component.day,Calendar.Component.hour,Calendar.Component.minute,Calendar.Component.second,Calendar.Component.weekday], from: date)
    return components
}

// MARK: - Date current
func XSQnowDate() -> String {
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    timeFormatter.locale = Locale.init(identifier: "zh_Hans_CN")
    timeFormatter.calendar = Calendar.init(identifier: .gregorian)
    let nowTime = timeFormatter.string(from: Date()) as String
    return nowTime
}

// MARK: - User defaults
func XSQud(key:String) -> String {
    let userDefaultString = UserDefaults.standard.string(forKey: key)
    return userDefaultString ?? ""
}

// MARK: - UITextField extension
func XSQsetTextFieldImage (textField: UITextField, icon: String) {
    textField.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
    textField.leftViewMode = UITextField.ViewMode.always
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 40))
    let IconView = UILabel(frame: CGRect(x: 10, y: 5, width: 30, height: 30))
    let paddingView = UIView(frame: CGRect(x: 0, y: 5, width: 10, height: 30))
    IconView.font = UIFont(name: "iconfont", size: 20)
    IconView.textColor = UIColor.white
    IconView.text = icon
    paddingView.backgroundColor = UIColor.clear
    view.addSubview(IconView)
    view.addSubview(paddingView)
    textField.leftView = view
    textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
}

// MARK: - Judge whether double
func judgeWhetherDouble(string: String) -> Bool {
    let scanner: Scanner = Scanner(string: string)
    var number:Double = 0
    return scanner.scanDouble(&number) && scanner.isAtEnd
}

// MARK: - Judge whether double
func getDoubleFromString(string: String) -> Double {
    let scanner = Scanner(string: string)
    scanner.scanUpToCharacters(from: CharacterSet.decimalDigits, into: nil)
    var number :Double = 0
    scanner.scanDouble(&number)
    return number
}

// MARK: - Set image url
@MainActor func setImageUrl(imageView: UIImageView, path: String?, placeHolder: String? = nil) {
    let url = URL(string: path ?? "")
    if let holder = placeHolder {
        imageView.kf.setImage(with: url, placeholder: UIImage(named: holder), options: nil, progressBlock: nil, completionHandler: nil)
    } else {
        imageView.kf.setImage(with: url)
    }
    
}
 
// MARK: - set background color
func setBackgroundColor() -> UIColor {
    if #available(iOS 13.0, *) {
        let backgroundColor = UIColor.systemBackground
        return backgroundColor
    } else {
        // Fallbåack on earlier versions
        let backgroundColor = UIColor.init(white: 0.97, alpha: 1)
        return backgroundColor
    }
}

// MARK: - Set text color
func setTextColor() -> UIColor {
    if #available(iOS 13.0, *) {
        let textColor = UIColor.label
        return textColor
    } else {
        // Fallback on earlier versions
        let textColor = UIColor.darkText
        return textColor
    }
}

// MARK: - First letter
func firstLetter(word:String) -> String {
    if word.count > 0 {
        let string:CFMutableString = CFStringCreateMutableCopy(nil, 0, word as CFString);
        CFStringTransform(string, nil, kCFStringTransformToLatin, false)
        CFStringTransform(string, nil, kCFStringTransformStripCombiningMarks, false)
        let letter = CFStringCreateWithSubstring(nil, string, CFRangeMake(0, 1))
        let big = (letter ?? ("#" as CFString)) as String
        return big.uppercased()
    }
    return "#"
}

// MARK: - Video crop picture
func VideoCropPicture(videoUrl: String, success: @escaping(_ image: UIImage) -> ()) {
    if videoUrl.count == 0 {
        return
    }
    guard let url = URL(string: videoUrl) else { return }
  
    DispatchQueue.global().async {
        let avAsset = AVURLAsset(url: url)
        let generator = AVAssetImageGenerator(asset: avAsset)
        generator.appliesPreferredTrackTransform = true
        let time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 600)
        var actualTime: CMTime = CMTimeMake(value: 0, timescale: 0)
        if let imageP = try? generator.copyCGImage(at: time, actualTime: &actualTime) {
            DispatchQueue.main.async {
                success(UIImage(cgImage: imageP))
            }
        }
    }
}

// MARK: - Log print
func XPLog<T>(message : T,file:String = #file ,function : String = #function, lineNum : Int = #line) {
    #if DEBUG
    let fileStr = (file as NSString).lastPathComponent
    let filePath = (function as NSString).lastPathComponent
    print("\(fileStr)---\(filePath)---[\(lineNum)]:- \(message)")
    #endif
}

// MARK: - Add corner
func addCorner(view: UIView, conrners: UIRectCorner, radius: CGFloat) {
    let maskPath = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: conrners, cornerRadii: CGSize(width: radius, height: radius))
    let maskLayer = CAShapeLayer()
    maskLayer.frame = view.bounds
    maskLayer.path = maskPath.cgPath
    view.layer.mask = maskLayer
}

func isSimulator() -> Bool {
    #if targetEnvironment(simulator)
    return true
    #else
    return false
    #endif
}

func getCurrentViewController() -> UIViewController? {
    guard let window = UIApplication.shared.delegate?.window ?? nil else {
        return nil
    }
    
    // 获取根控制器
    var currentViewController = window.rootViewController
    
    while true {
        if let presentedVC = currentViewController?.presentedViewController {
            currentViewController = presentedVC
        } else if let navigationController = currentViewController as? UINavigationController {
            currentViewController = navigationController.viewControllers.last
        } else if let tabBarController = currentViewController as? UITabBarController {
            currentViewController = tabBarController.selectedViewController
        } else {
            if let childViewControllers = currentViewController?.children, childViewControllers.count > 0 {
                currentViewController = childViewControllers.last
            }
            break
        }
    }
    return currentViewController
}
import CommonCrypto
public extension String {
    /**
     - returns: the String, as an MD5 hash.
     */
    var md5: String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        
        let hash = NSMutableString()
        
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        
        result.deallocate()
        return hash as String
    }
    
    
}
extension String {
    func stringBoundingRect(width: CGFloat, fontSize: CGFloat) -> CGFloat {
        let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: fontSize)]
        // 计算出 string 的高度
        let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let textHeight = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size.height
        return textHeight + 1
    }
}

//MARK:- 颜色设置
extension UIColor{
    static func colorWithRGB(red:CGFloat,green:CGFloat,blue:CGFloat,alpha:CGFloat = 1.0) -> UIColor{
        
        return UIColor.init(red: (red)/CGFloat(255), green: (green)/CGFloat(255), blue: (blue)/CGFloat(255), alpha: alpha)
        
    }
    
    //    kRGBColorFromHex(0x1D1D26)
    func colorConversionHex (Color_Value:NSString, alpha: CGFloat = 1.0)->UIColor{
        var  Str :NSString = Color_Value.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased() as NSString
        
        if Color_Value.hasPrefix("#"){
            Str=(Color_Value as NSString).substring(from: 1) as NSString
        }
        let redStr = (Str as NSString ).substring(to: 2)
        let greenStr = ((Str as NSString).substring(from: 2) as NSString).substring(to: 2)
        let blueStr = ((Str as NSString).substring(from: 4) as NSString).substring(to: 2)
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string:redStr).scanHexInt32(&r)
        Scanner(string: greenStr).scanHexInt32(&g)
        Scanner(string: blueStr).scanHexInt32(&b)
        return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: alpha)
    }
}

extension UIView {
    func setShadow(cornerRadius: CGFloat? = nil, offset: CGSize? = nil) {
        self.layer.cornerRadius = cornerRadius ?? 10
        self.layer.shadowOffset = offset ?? CGSize(width: 0, height: 2)
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOpacity = 0.1;//阴影透明度，默认0
        self.layer.shadowRadius = 1;//阴影半径，默认3
    }
    
    func setupGradientBackground(startColor: UIColor, endColor: UIColor, startPoint: CGPoint, endPoint: CGPoint) {
        // 创建渐变图层
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds
        
        // 设置渐变颜色
        let startColor = startColor.cgColor
        let endColor = endColor.cgColor
        gradientLayer.colors = [startColor, endColor]
        
        // 设置渐变方向
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        
        // 将渐变图层添加到按钮的图层上
        self.layer.insertSublayer(gradientLayer, at: 0)
    }

}

extension UIViewController {
    func showHUDOnlyShowMessage(messge:String,duration:Int = 1){
        //        SVProgressHUD.showOnlyLabel(withStatus: messge)
        //        KBProgresHUD.showTypeBlackTimeIntervalNotImg(20, withStatus: messge)
        //        kbpr
        SVProgressHUD.show(UIImage(), status: messge)
        SVProgressHUD.setFont(UIFont.systemFont(ofSize: 14))
        SVProgressHUD.setBackgroundColor(UIColor.black)
        SVProgressHUD.setCornerRadius(10)
        SVProgressHUD.setForegroundColor(UIColor.white)
        SVProgressHUD.setImageViewSize(CGSize.init(width: 0, height: 0))
        SVProgressHUD.setDefaultMaskType(.custom)

//        SVProgressHUD.setInfoImage(UIImage())
//        SVProgressHUD.showInfo(withStatus: messge)
//        SVProgressHUD.show(<#T##image: UIImage##UIImage#>, status: <#T##String?#>)
    }
}
